import 'dart:async';
import 'dart:io';

import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pip_flutter/pipflutter_player_configuration.dart';
import 'package:pip_flutter/pipflutter_player_controller.dart';
import 'package:pip_flutter/pipflutter_player_data_source.dart';

class StreamPipController extends GetxController {
  PipFlutterPlayerController? pipFlutterPlayerController;

  bool needJump = true; //

  late Timer? timer = null;

  void initStreamPipController(String url) {
    if (Platform.isIOS) {
      if (timer != null) {
        timer?.cancel();
      } else {
        PipFlutterPlayerConfiguration pipFlutterPlayerConfiguration =
            const PipFlutterPlayerConfiguration(
          aspectRatio: 667 / 375,
          fit: BoxFit.cover,
        );
        pipFlutterPlayerController =
            PipFlutterPlayerController(pipFlutterPlayerConfiguration);
        pipFlutterPlayerController!
            .setupDataSource(PipFlutterPlayerDataSource.network(url));
        CustomToast.show("视频加载需要几秒，请稍等...", length: ToastLength.LENGTH_LONG);
        timer = Timer(Duration(seconds: 3), () {
          enablePictureInPicture();
        });
      }
    }
  }

  void enablePictureInPicture() {
    if (pipFlutterPlayerController != null) {
      needJump = true;
      pipFlutterPlayerController!.enablePictureInPicture();
    }
  }

  Future<bool> isPictureInPictureSupported() async {
    if (pipFlutterPlayerController != null) {
      return pipFlutterPlayerController!.isPictureInPictureSupported();
    }
    return false;
  }

  //销毁控制器也可以用来关闭控制器
  onDispose() {
    pipFlutterPlayerController!.dispose(forceDispose: true);
    pipFlutterPlayerController = null;
  }

  disPipPlayer() {
    if (Platform.isIOS && pipFlutterPlayerController != null) {
      needJump = false;
      if (timer != null) {
        timer?.cancel();
        timer = null;
      }
      pipFlutterPlayerController!.disablePictureInPicture();
      onDispose();
    }
  }
}
